import { OrgTree } from '@/pages/organization/components/tree';
import { Divider } from 'antd';
import { GTable, GTableSchema } from 'geminis-react';
import { useCallback, useRef } from 'react';
import styles from './components/tree.less';

export default () => {
  const tree = useRef<any>();
  const table = useRef<any>();

  const onTreeSelected = useCallback(
    ({ selectedKeys }: any) => {
      table.current.loadData(
        selectedKeys[0] === ''
          ? { parentIdIsNull: true }
          : { parentId: selectedKeys[0] },
      );
    },
    [table],
  );

  const reloadTree = useCallback(() => {
    tree.current.reloadSelectedNode();
  }, []);

  const setParentPath = useCallback((value: any) => {
    const selectedData = tree.current.selection.selectedNodes[0].data;
    value.parentId = selectedData.id === '' ? null : selectedData.id;
    value.parentPath = selectedData.pathId;
  }, []);

  const schema: GTableSchema = {
    headerTitle: '机构信息',
    data: {
      url: '/api/resources/organization',
      sort: ['showOrder:asc'],
    },
    manualRequest: true,
    action: {
      toolbar: {
        add: {
          form: {
            schemaPath: '/resources-pc/schema/organization/edit.json',
            onSubmitting: setParentPath,
            onSubmitted: reloadTree,
          },
        },
        delete: true,
      },
      row: {
        edit: true,
        delete: true,
      },
    },
  };

  return (
    <div className={styles.main}>
      <div className={styles.tree}>
        <OrgTree ref={tree} showRoot={true} onSelected={onTreeSelected} />
      </div>
      <Divider type="vertical" className={styles.fullHeight} />
      <div className={styles.content}>
        <GTable
          ref={table}
          schemaPath="/resources-pc/schema/organization/table.json"
          schema={schema}
          onDeleted={reloadTree}
        />
      </div>
    </div>
  );
};
